// pages/cart/cart.js
import { getSetting, chooseAddress } from '../../utils/info.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        cartList: [],
        totalNum: 0,
        totalPrice: 0,
        check: false,
        // 地址信息
        address: {},
    },

    /**
     * 获取商品列表
     */
    getCartList() {
        const cartList = wx.getStorageSync('cart') || [];
        const total = {
            totalPrice: 0,
            totalNum: 0,
            check: true
        }
        cartList.forEach(v => {
            if (v.checked) {
                total.totalPrice += v.num * v.goods_price
                total.totalNum += v.num
            } else {
                total.check = false
            }
        });

        if (!cartList.length) {
            total.check = false
        }


        this.setData({
            cartList, ...total
        })


    },

    /**
     * 收货地址
     */
    async getAddress() {

        const userInfo = wx.getStorageSync('userInfo')
        const token = wx.getStorageSync('token')
        if (!Object.keys(userInfo).length || !token) return wx.navigateTo({
            url: '/pages/info/info'
        })

        // 获取设备权限
        const { authSetting } = await getSetting()
        if (authSetting['scope.address'] !== true) return

        // 获取收货地址
        const { provinceName, cityName, countyName, detailInfo, telNumber, userName } = await chooseAddress()

        const address = {
            all: provinceName + cityName + countyName + detailInfo,
            telNumber,
            userName
        }
        wx.setStorageSync('address', address);
    },

    /**
     * 修改商品数量
     */
    onChange(e) {
        const num = e.detail;
        const index = e.currentTarget.dataset.index;
        this.data.cartList[index].num = num;
        wx.setStorageSync('cart', this.data.cartList)
        this.getCartList()
    },

    /**
     * 删除单个商品
     */
    delGoods(e) {
        const that = this;
        wx.showModal({
            title: '提示',
            content: '您确定要删除此商品吗？',
            success(res) {
                if (res.confirm) {
                    const index = e.currentTarget.dataset.index;
                    that.data.cartList.splice(index, 1);
                    wx.setStorageSync('cart', that.data.cartList)
                    that.getCartList()
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                    })
                } else if (res.cancel) {
                    wx.showToast({
                        title: '取消删除',
                        icon: 'none',
                    })
                }
            }
        })
    },

    /**
     * 单选
     */
    checkOne(e) {
        const flag = e.detail
        const index = e.currentTarget.dataset.index;
        this.data.cartList[index].checked = flag;
        wx.setStorageSync('cart', this.data.cartList)
        this.getCartList()
    },

    /**
     * 全选
     */
    checkAll(e) {
        const flag = e.detail
        this.setData({
            check: flag
        })
        this.data.cartList.forEach(item => item.checked = flag)
        wx.setStorageSync('cart', this.data.cartList)
        this.getCartList()
    },

    /**
     * 提交订单
     */
    onClickButton() {
        const { cartList } = this.data;
        const flag = cartList.some(item => item.checked)
        const { address } = this.data
        if (!Object.keys(address).length) return wx.showToast({
            title: '请选择收货地址',
            icon: 'none',
        })
        if (!flag) return wx.showToast({
            title: '请选择商品',
            icon: 'none',
        })

        wx.navigateTo({
            url: '/pages/pay/pay',
        })

    },

    /**
     * 跳转到商品详情页
     */
    goGoodDefault(e) {
        try {
            const goodsId = e.currentTarget.dataset.goods_id
            wx.navigateTo({
                url: `../default/default?goodsId=${goodsId}`
            })
        } catch (error) {
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getCartList()

        const address = wx.getStorageSync('address') || {}
        this.setData({
            address
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})